#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
确保所有模板文件都有{% load static %}标签
"""
import os
import re
from pathlib import Path


def ensure_load_static(file_path):
    """确保模板文件有{% load static %}"""
    print(f"检查: {file_path}")
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    original_content = content
    
    # 检查文件是否继承了base.html或使用了static标签
    has_extends = '{% extends' in content
    uses_static = '{% static' in content
    has_load_static = '{% load static %}' in content
    
    # 如果使用了static标签但没有load static,则添加
    if uses_static and not has_load_static:
        lines = content.split('\n')
        
        # 找到extends语句后的位置
        insert_index = 0
        for i, line in enumerate(lines):
            if '{% extends' in line:
                insert_index = i + 1
                break
        
        # 在extends之后插入{% load static %}
        if insert_index > 0:
            # 检查下一行是否已经是空行
            if insert_index < len(lines) and lines[insert_index].strip() == '':
                lines[insert_index] = '{% load static %}'
            else:
                lines.insert(insert_index, '{% load static %}')
        else:
            # 如果没有extends,在文件开头插入
            lines.insert(0, '{% load static %}')
        
        content = '\n'.join(lines)
    
    if content != original_content:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print("✓ 已添加{{% load static %}}: " + str(file_path))
        return True
    else:
        print(f"- 无需修改: {file_path}")
        return False


def process_all_templates(templates_dir):
    """处理所有模板文件"""
    templates_path = Path(templates_dir)
    
    if not templates_path.exists():
        print(f"错误: 模板目录不存在: {templates_dir}")
        return
    
    html_files = list(templates_path.rglob('*.html'))
    total_files = len(html_files)
    fixed_files = 0
    
    print(f"\n找到 {total_files} 个HTML模板文件")
    print("=" * 60)
    
    for html_file in html_files:
        if ensure_load_static(html_file):
            fixed_files += 1
    
    print("=" * 60)
    print(f"\n处理完成!")
    print(f"总文件数: {total_files}")
    print(f"已修改: {fixed_files}")
    print(f"无需修改: {total_files - fixed_files}")


if __name__ == '__main__':
    project_root = Path(__file__).parent
    templates_dir = project_root / 'templates'
    
    print("=" * 60)
    print("Django模板{% load static %}检查工具")
    print("=" * 60)
    
    process_all_templates(templates_dir)
    
    print("\n✅ 所有模板文件已处理完成!")
